package _10匿名内部类创建线程;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.awt.event.ActionEvent;

public class MyFrame1 extends JFrame {

	private JPanel contentPane;
	
	Thread t1;
	
	boolean running;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MyFrame1 frame = new MyFrame1();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MyFrame1() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblNewLabel = new JLabel("New label");
		lblNewLabel.setBounds(31, 20, 105, 31);
		contentPane.add(lblNewLabel);
		
		JButton btnNewButton = new JButton("开始");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				t1 = new Thread(new Runnable() {
					
					@Override
					public void run() {

						running = true;
						while(running)
						{
							Date d1 = new Date();
							DateFormat df = new SimpleDateFormat("HH:mm:ss");
							lblNewLabel.setText(df.format(d1));
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				});
				t1.start();
				
				
			}
		});
		btnNewButton.setBounds(160, 24, 93, 23);
		contentPane.add(btnNewButton);
		
		JButton btnNewButton_1 = new JButton("停止");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				// 终止线程的运行
				
				// 方式1: (已过时，不推荐)
//				t1.stop();
				
				// 方式2: (已过时，不推荐)
//				t1.suspend();
				
				// 方式3:
				running = false;
				
				
			}
		});
		btnNewButton_1.setBounds(160, 69, 93, 23);
		contentPane.add(btnNewButton_1);
		
		
	}
}
